﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxEditors;
using TravelLink.DAL;
using Interactive.Utility.Extension;
using TravelLink.Common;
namespace TravelLink.WebApp.Admin {
    public partial class AdminPosition : System.Web.UI.Page, ICallbackEventHandler {
        protected void Page_Load(object sender, EventArgs e) {
            if (!this.IsPostBack)
            {
                this.CheckResponse("3001");
                if ((this.Request.QueryString["PositionCode"] ?? "") != string.Empty)
                {
                    this.LinqDataSource1.Where = "PositionCode=@PositionCode";
                    this.LinqDataSource1.WhereParameters.Add("PositionCode", System.Data.DbType.Guid, this.Request.QueryString["PositionCode"]);
                }
            }
            else
            {
                this.btnSerach_Click(null, null);
            }
        }

        protected void btnSerach_Click(object sender, EventArgs e) {
            this.LinqDataSource1.Where = "1=1";
            if (!string.IsNullOrEmpty(this.aspPeroidBegin.Text)) {
                this.LinqDataSource1.Where += "&&PeriodTo>@PeriodToBegin";
                this.LinqDataSource1.WhereParameters.Add("PeriodToBegin", System.Data.DbType.DateTime, this.aspPeroidBegin.Date.ToString("yyyy-MM-dd 00:00:00"));
            }
            if (!string.IsNullOrEmpty(this.aspPeroidEnd.Text)) {
                this.LinqDataSource1.Where += "&&PeriodTo<@PeriodToEnd";
                this.LinqDataSource1.WhereParameters.Add("PeriodToEnd", System.Data.DbType.DateTime, this.aspPeroidEnd.Date.ToString("yyyy-MM-dd 23:59:59"));
            }
            if (!string.IsNullOrEmpty(this.adefrom.Text)) {
                this.LinqDataSource1.Where += "&&PublishDate>@PublishDateBegin";
                this.LinqDataSource1.WhereParameters.Add("PublishDateBegin", System.Data.DbType.DateTime, this.adefrom.Date.ToString("yyyy-MM-dd 00:00:00"));
            }
            if (!string.IsNullOrEmpty(this.adeto.Text)) {
                this.LinqDataSource1.Where += "&&PublishDate<@PublishDateEnd";
                this.LinqDataSource1.WhereParameters.Add("PublishDateEnd", System.Data.DbType.DateTime, this.adeto.Date.ToString("yyyy-MM-dd 23:59:59"));
            }
            if (!string.IsNullOrEmpty(this.atbkey.Text)) {
                this.LinqDataSource1.Where += "&&((PositionName+CompanyName).Contains(@key)|| Department.Contains(@key)|| Description.Contains(@key))";
                this.LinqDataSource1.WhereParameters.Add("key", System.Data.DbType.String, this.atbkey.Text);
            }

            if (this.cmxPositionType.SelectedIndex > 0) {
                this.LinqDataSource1.Where += "&&PositionType==@PositionType";
                this.LinqDataSource1.WhereParameters.Add("PositionType", System.Data.DbType.Int32, this.cmxPositionType.Value.ToString());
            }

            if (this.cbxCompany.SelectedIndex > 0) {
                this.LinqDataSource1.Where += "&&CompanyCode==@CompanyCode";
                this.LinqDataSource1.WhereParameters.Add("CompanyCode", System.Data.DbType.Guid, this.cbxCompany.Value.ToString());
            }
        }

        protected void ASPxGridView1_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e) {
            Guid pGuid = new Guid(e.Keys[0].ToString());
            var db = TravelLink.DAL.DataContextFactory.Create();
            var enttiy = db.TL_Company_Position.Where(u => u.PositionCode == pGuid).FirstOrDefault();
            if (enttiy != null) {
                db.TL_Company_Position.DeleteOnSubmit(enttiy);
                db.SubmitChanges();
            }
        }

        protected void ASPxGridView1_RowDeleted(object sender, DevExpress.Web.Data.ASPxDataDeletedEventArgs e) {
            e.ExceptionHandled = true;
        }

        protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e) {
            var tiem = e.NewValues;
        }

        protected void ASPxGridView1_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e) {

        }

        protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
            var tiem = e.NewValues;
        }

        protected void ASPxGridView1_RowUpdated(object sender, DevExpress.Web.Data.ASPxDataUpdatedEventArgs e) {

        }

        protected void btnSave_Click(object sender, EventArgs e) {
            var txtOtherInfo = this.ASPxGridView1.FindEditFormTemplateControl("txtOtherInfo") as ASPxMemo;
            var hidPositionCode = this.ASPxGridView1.FindEditFormTemplateControl("hidPositionCode") as HiddenField;
            var txtNumber = this.ASPxGridView1.FindEditFormTemplateControl("txtNumber") as DevExpress.Web.ASPxEditors.ASPxTextBox;
            var txtPostionName = this.ASPxGridView1.FindEditFormTemplateControl("txtPostionName") as DevExpress.Web.ASPxEditors.ASPxTextBox;
            var txtReportTo = this.ASPxGridView1.FindEditFormTemplateControl("atbReportTo") as DevExpress.Web.ASPxEditors.ASPxTextBox;
            var cbxCompany = this.ASPxGridView1.FindEditFormTemplateControl("ASPxComboBox1") as DevExpress.Web.ASPxEditors.ASPxComboBox;
            var cbxPositionType = this.ASPxGridView1.FindEditFormTemplateControl("cbxPositionType") as DevExpress.Web.ASPxEditors.ASPxComboBox;
            var txtDepartment = this.ASPxGridView1.FindEditFormTemplateControl("txtDepartment") as DevExpress.Web.ASPxEditors.ASPxTextBox;
            var cmdPositionLevel = this.ASPxGridView1.FindEditFormTemplateControl("cmdPositionLevel") as DevExpress.Web.ASPxEditors.ASPxComboBox;
            var txtLimtDate = this.ASPxGridView1.FindEditFormTemplateControl("txtLimtDate") as DevExpress.Web.ASPxEditors.ASPxTextBox;
            var cbxWorkTypeId = this.ASPxGridView1.FindEditFormTemplateControl("cbxWorkTypeId") as DevExpress.Web.ASPxEditors.ASPxComboBox;
            var cbxCity = this.ASPxGridView1.FindEditFormTemplateControl("cbxCity") as DevExpress.Web.ASPxEditors.ASPxComboBox;
            var txtSalary = this.ASPxGridView1.FindEditFormTemplateControl("txtSalary") as DevExpress.Web.ASPxEditors.ASPxTextBox;
            var cbxStatus = this.ASPxGridView1.FindEditFormTemplateControl("cbxStatus") as DevExpress.Web.ASPxEditors.ASPxComboBox;
            var txtPeriodTo = this.ASPxGridView1.FindEditFormTemplateControl("txtPeriodTo") as DevExpress.Web.ASPxEditors.ASPxDateEdit;
            var txtRequirement = this.ASPxGridView1.FindEditFormTemplateControl("txtRequirement") as DevExpress.Web.ASPxEditors.ASPxMemo;
            var txtDescription = this.ASPxGridView1.FindEditFormTemplateControl("txtDescription") as DevExpress.Web.ASPxEditors.ASPxMemo;

            TL_Company_Position updateEntity = null;
            var db = DataContextFactory.Create();
            if (string.IsNullOrEmpty(hidPositionCode.Value)) {
                updateEntity = new TL_Company_Position();
                updateEntity.PositionCode = Guid.NewGuid();
                updateEntity.PublishDate = DateTime.Now;

                updateEntity.PublishPerson = "";
            }
            else {

                Guid pCode = new Guid(hidPositionCode.Value);
                updateEntity = db.TL_Company_Position.Where(u => u.PositionCode == pCode).FirstOrDefault();
            }

            updateEntity.CompanyCode = new Guid(cbxCompany.Value.AsStr(Guid.Empty.ToString()));
            updateEntity.Department = txtDepartment.Text;
            updateEntity.Description = txtDescription.Text;
            updateEntity.LimtDate = txtLimtDate.Text;
            updateEntity.Number = txtNumber.Text.AsInt(0);
            updateEntity.OtherInfo = txtOtherInfo.Text;
            updateEntity.PeriodTo = txtPeriodTo.Date;
            updateEntity.ReportTo = txtReportTo.Text;
            updateEntity.PositionLevel = cmdPositionLevel.SelectedIndex >= 0 ? new int?(cmdPositionLevel.Value.AsInt()) : null;
            updateEntity.PositionName = txtPostionName.Text;
            updateEntity.PositionType = cbxPositionType.SelectedIndex >= 0 ? new int?(cbxPositionType.Value.AsInt()) : null;

            updateEntity.Requirement = txtRequirement.Text;
            updateEntity.Salary = txtSalary.Text;
            updateEntity.Status = cbxStatus.Value.AsInt();
            updateEntity.WorkInCityId = cbxCity.SelectedIndex >= 0 ? new int?(cbxCity.Value.AsInt()) : null;
            updateEntity.WorkTypeId = cbxWorkTypeId.SelectedIndex >= 0 ? new int?(cbxWorkTypeId.Value.AsInt()) : null;

            if (string.IsNullOrEmpty(hidPositionCode.Value)) {
                db.TL_Company_Position.InsertOnSubmit(updateEntity);
            }
            db.SubmitChanges();


            this.ASPxGridView1.CancelEdit();        
        }

        protected void cmxPositionType_DataBound(object sender, EventArgs e) {
            this.cmxPositionType.Items.Insert(0, new ListEditItem("全部", "-1"));
        }

        protected void cbxCompany_DataBound(object sender, EventArgs e) {
            this.cbxCompany.Items.Insert(0, new ListEditItem("全部", Guid.Empty.ToString()));
        }

        protected void abtnExport_Click(object sender, EventArgs e) {
            this.ASPxGridViewExporter1.WriteXlsToResponse(true);
        }

        protected void btnSerachUser_Click(object sender, EventArgs e) {
            this.ldsUser.Where = "1==1";
            if (this.atbusermail.Text.Trim() != string.Empty) {

                this.ldsUser.Where += "&&Email==@Mail";
                this.ldsUser.WhereParameters.Add("Mail", this.atbusermail.Text);
            }
            if (this.atbusermobile.Text.Trim() != string.Empty) {
                this.ldsUser.Where += "&&Mobile==@Mobile";
                this.ldsUser.WhereParameters.Add("Mobile", this.atbusermobile.Text);
            }
            if (this.atbusercode.Text.Trim() != string.Empty) {
                this.ldsUser.Where += "&&UserCode==@UserCode";
                this.ldsUser.WhereParameters.Add("UserCode", this.atbusercode.Text);
            }
        }
        private string CallBackValue = string.Empty;
        #region ICallbackEventHandler 成员

        public string GetCallbackResult() {
            return CallBackValue;
        }

        public void RaiseCallbackEvent(string eventArgument) {
            try {
                int idx = int.Parse(eventArgument.Split('|')[0]);
                int func = int.Parse(eventArgument.Split('|')[1]);
                View_CompanyPosition obj = (View_CompanyPosition)this.ASPxGridView1.GetRow(idx);
                if (func == 1)
                {                   
                    List<string> tolist = new List<string>();
                    for (int i = 0; i < this.ASPxGridView2.VisibleRowCount; i++)
                    {
                        string content = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>职位信息</title>
<style type='text/css'>
<!--
body { margin: 0 auto; font-size:12px;}
li,dl{list-style-type:none; margin:0; padding:0;vertical-align:top;}
a:link,a:visited{color:#000000;text-decoration: none;}
a:hover {color: #cd0000;text-decoration: none;}
a:active {text-decoration: none;}

#job_box{ width:611px; margin: 0 auto; padding-top:15px;}
#job_left1{ width:5px; float:left; background:url(http://www.travellinkrecruitment.com/img/job_pic_03.jpg); height:781px;}
#job_conten1{ width:599px;_width:597px ; height:781px; float:left; border:1px solid #d1d1d1;}
#job_right1{ width:5px; float:right;background:url(http://www.travellinkrecruitment.com/img/job_pic_05.jpg); height:781px;}
#job_c_top{ width:599px; _width:597px; margin-top:33px; text-align:center;}
#job_c_block{ width:568px; height:10px; margin:0 auto; padding-top:11px;}
#job_c_words{ width:556px; font-size:12px; color:#757474; padding:25px 0 0 45px; line-height:20px;}
#job_c_refer{ width:556px; padding-left:45px; color:#5a479a; padding-top:15px;}
#job_c_picc{ width:568px; height:37px !important; background:url(http://www.travellinkrecruitment.com/img/job_pic_17.jpg);  margin:13px 0 0 15px;}
#job_news_zp{ width:568px; height:52px;margin:25px 0 0 15px;}
.job_name{ font-size:14px;  display:block; height:8px;}
.job_picc_change{ text-align:right; display:block; line-height:40px; color:#d1d1d1; padding-right:17px;}
#job_news_zp_titel{ width:500px; display:block; font-size:14px; color:#493292; font-weight:bold; padding-left:10px;}
#job_news_zp_recr{ width:480px; height:24px; padding:12px 0 0 10px; color:#020000; float:left;}
#job_news_zp_view{ float:right; width:69px; height:12px; margin-top:14px;}
#job_news_zp_ine{ width:568px; height:1px;}
#job_bottom{ width:479px; margin:40px 0 0 50px;}
.job_bm_left{ float:left; margin-top:5px;}
.job_bm_right{ float:right; padding-left:15px;}
-->
</style></head>
<body>
 <div id='job_box'>
     <div id='job_left1'></div>
     <div id='job_conten1'>
      <div id='job_c_top'><img src='http://www.travellinkrecruitment.com/img/job_pic_08.jpg' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       <img src='http://www.travellinkrecruitment.com/img/job_pic_11.jpg' width='207' height='25' /></div>
      <div id='job_c_block'><img src='http://www.travellinkrecruitment.com/img/job_pic_15.jpg' width='568' height='10' /></div>
       <div id='job_c_words'>
       <span class='job_name'>@name， 您好！</span>
         <br />
         旅业链接&nbsp;|&nbsp;招聘旨在为旅游行业的个人和企业寻求发展提供更广阔的天地。
         <br />
       为旅游业内人士提供更好的职业发展机会，为业内企业招募优秀人才，是我们的不懈追求！</div>
       <div id='job_c_refer'><a href='http://www.travellinkrecruitment.com/' style='color:#5a479a;'>敬请查阅您在旅业链接</a>&nbsp;|&nbsp;<a href='http://www.travellinkrecruitment.com/' style='color:#5a479a;'>招聘网站订阅职位信息如下</a></div>
       <div id='job_c_picc'><span class='job_picc_change'><a href='http://www.travellinkrecruitment.com/' style='color:#d1d1d1;'>更改</a>/
       <a href='http://www.travellinkrecruitment.com/' style='color:#d1d1d1;'>取消您的订阅</a></span></div>
       <div id='job_news_zp'> 
       <div id='job_news_zp_titel'>@title</div>
       <div id='job_news_zp_recr'>@content</div>
       <div id='job_news_zp_view'><a href='@joburl'><img src='http://www.travellinkrecruitment.com/img/job_pic_20.jpg' width='69' height='12' border='0' /></a></div>
         <div id='job_news_zp_ine'><img src='http://www.travellinkrecruitment.com/img/job_pic_19.jpg' /></div>
      </div>
      <div id='job_bottom'>
      <div class='job_bm_left'><a href='http://www.travellinkrecruitment.com/'><img src='http://www.travellinkrecruitment.com/img/job_pic_29.jpg' border='0' /></a></div>
         <div class='job_bm_right'><a href='http://www.travellinkrecruitment.com/'><img src='http://www.travellinkrecruitment.com/img/job_pic_26.jpg' width='118' height='38' border='0' /></a></div>
       </div>
  </div>
     <div id='job_right1'></div>
 </div>
</body>

</html>
";
                        TL_User d = (TL_User)this.ASPxGridView2.GetRow(i);
                        if (d.Email != null && d.Email.Trim() != string.Empty)
                        {
                            tolist.Add(d.Email);
                        }
                        if (tolist.Count > 0)
                        {
                            //@name 姓名
                            content = content.Replace("@name", (d.CFirstName ?? "") + (d.CLastName ?? ""));
                            //@title 企业名
                            string title = obj.CompanyName;
                            content = content.Replace("@title", title);
                            //@content 职位|Department|地点
                            string ctt = string.Format("{0}|{1}|{2}",obj.PositionName,obj.Department,obj.CityName);
                            content = content.Replace("@content", ctt);
                            //@joburl
                            string joburl = string.Format("http://www.travellinkrecruitment.com/PositionDetail.aspx?pc={0}",obj.PositionCode);
                            content = content.Replace("@joburl", joburl);
                            MailSender.SendMailByRecommend(content, tolist);
                        }
                    }                    
                }
                else
                {
                    var dc=DataContextFactory.Create();
                    int sortid = (dc.TL_HotPosition.Max(t=>t.SortId)??1);
                    TL_HotPosition hp = new TL_HotPosition();
                    hp.SortId = sortid;
                    hp.PositionCode = obj.PositionCode;
                    hp.Image = string.Empty;
                    dc.TL_HotPosition.InsertOnSubmit(hp);
                    dc.SubmitChanges();
                }
                CallBackValue = "";
            }
            catch (Exception ex) {
                this.CallBackValue = ex.Message;
            }
        }



        #endregion

        /// <summary> 
        /// 检测输入的邮件地址strEmail是否合法，非法则返回true。 
        /// </summary> 
        public bool CheckEmail(string strEmail) {
            int i, j;
            string strTmp, strResult;
            string strWords = "abcdefghijklmnopqrstuvwxyz_-.0123456789"; //定义合法字符范围 
            bool blResult = false;
            strTmp = strEmail.Trim();
            //检测输入字符串是否为空，不为空时才执行代码。 
            if (!(strTmp == "" || strTmp.Length == 0)) {
                //判断邮件地址中是否存在“@”号 
                if ((strTmp.IndexOf("@") < 0)) {
                    blResult = true;
                    return blResult;
                }
                //以“@”号为分割符，把地址切分成两部分，分别进行验证。 
                string[] strChars = strTmp.Split(new char[] { '@' });
                foreach (string strChar in strChars) {
                    i = strChar.Length;
                    //“@”号前部分或后部分为空时。 
                    if (i == 0) {
                        blResult = true;
                        return blResult;
                    }
                    //逐个字进行验证，如果超出所定义的字符范围strWords，则表示地址非法。 
                    for (j = 0; j < i; j++) {
                        strResult = strChar.Substring(j, 1).ToLower();//逐个字符取出比较 
                        if (strWords.IndexOf(strResult) < 0) {
                            blResult = true;
                            return blResult;
                        }
                    }
                }
            }
            return blResult;
        }
    }
}